package cn.zzuisa.news.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zzuisa.news.entity.IprNewsInfo;
import cn.zzuisa.news.entity.IprNewsItem;
import cn.zzuisa.news.entity.Page;
import cn.zzuisa.news.service.IprNewsService;
import cn.zzuisa.news.service.impl.IprNewsServiceImpl;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet(name = "index", urlPatterns = "/index", asyncSupported = true)
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IprNewsService iprNewsServiceImpl = new IprNewsServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if (method == null) {
			List<IprNewsInfo> listinfo = iprNewsServiceImpl.listinfoByType(null);
			req.setAttribute("list", listinfo);
			req.getRequestDispatcher("WEB-INF/ftl/index/indexNews.ftl").forward(req, resp);

		} else if (method.equals("list")) {
			String type = req.getParameter("type");
			Integer current;
			Integer size;
			Page page = null;
			List<String> types, typesid = null;
			try {
				current = Integer.parseInt(req.getParameter("page"));
				size = Integer.parseInt(req.getParameter("size"));
			} catch (NumberFormatException e) {
				current = 1;
				size = 10;
			}
			String sql = "type = " + type + " and";
			page = iprNewsServiceImpl.page(current, size, sql);
			page.setPageNo(current);
			types = iprNewsServiceImpl.showTypes();
			typesid = iprNewsServiceImpl.showTypesId();
			req.setAttribute("lists", page);
			req.setAttribute("types", types);
			req.setAttribute("typesid", typesid);
			req.getRequestDispatcher("WEB-INF/ftl/Ipr/list.ftl").forward(req, resp);
		} else if (method.equals("detail_page")) {
			Integer id = Integer.parseInt(req.getParameter("id"));
			IprNewsItem iprNewsItem = iprNewsServiceImpl.findById(id);
			req.setAttribute("news", iprNewsItem);
			req.getRequestDispatcher("WEB-INF/ftl/Ipr/detail.ftl").forward(req, resp);
		}
	}

}
